package com.aivin.lib_readnotes.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.WebView;
import android.widget.CheckBox;
import android.widget.ScrollView;
import android.widget.TextView;

import com.aivin.lib_base.config.SaveConfig;
import com.aivin.lib_base.tool.DelTagsUtil;
import com.aivin.lib_base.tool.RouteUtils;
import com.aivin.lib_base.tool.WkLog;
import com.aivin.lib_reader.icallback.SettingCallBack;
import com.aivin.lib_reader.view.ReadSettingPopuWindow;
import com.aivin.lib_readnotes.R;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.gyf.immersionbar.ImmersionBar;
import com.tencent.mmkv.MMKV;
import com.wk.bmoblib.bean.Paper;
import com.wk.bmoblib.tool.DataTool;

import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;


/**
 * 具体的阅读器界面
 */
@Route(path = RouteUtils.PaperActivity)
public class PaperActivity extends Activity {

    private WebView webView ;
    private TextView infoTv ;
    private int bookIndex ,chapterIndex   ;
    private CheckBox radioBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reader);

        ImmersionBar.with(this)
                .fitsSystemWindows(true)
                .statusBarColor( R.color.color_2e4a7e)
                .init();
        initView();

        String jsonStr = getIntent().getStringExtra("jsonStr"  );
        Paper item = JSON.parseObject(jsonStr, Paper.class);

        bookIndex = item.getBookIndex();
        chapterIndex = item.getChapterIndex();
        getDataFromeServer(chapterIndex ,false); // onCreate
    }


    private void getDataFromeServer(int chapterIndex0 , boolean isLoadNextOrPre){
        chapterIndex = chapterIndex0 <=0 ?  0: chapterIndex0 ;//防止无效id
        infoTv.setText(getText(R.string.str_isloading));
        infoTv.setTextColor(Color.parseColor("#008000"));
        getChapters(bookIndex ,chapterIndex) ;
    }


    public void getChapters( int bookIndex ,int chapterIndex ){
        BmobQuery<Paper> bmobQuery = new BmobQuery<Paper>();
        bmobQuery.addWhereEqualTo("bookIndex", bookIndex);
        bmobQuery.addWhereEqualTo("chapterIndex", chapterIndex);
        bmobQuery.setLimit(5000) ;
        bmobQuery.order("chapterIndex") ;

        bmobQuery.findObjects(new FindListener<Paper>() {
            @Override
            public void done(List<Paper> data, BmobException e) {

                if(data != null && data.size()>0 )   {
                    Paper paper =  data.get(0);

                    infoTv.setVisibility(View.GONE);
                    String content =paper.getData() ;

                    WkLog.showLog("content---->"+content+"<---");
                    if(content==null|| content.equals("")  ){
                        content= getString(R.string.str_dataIsnull) ;
                    }

                    content = content.replaceAll("<br/>" ,"");
                    webView.loadDataWithBaseURL(null, content, "text/html", "utf-8", null);

                    String realData = DelTagsUtil.getTextFromHtml(content) ;
                    dataSize= realData.length();

                    DataTool.getInstance().addReadCount(paper  );
                }else{
                    infoTv.setTextColor(Color.RED);
                    infoTv.setText( getString(R.string.str_dataIsNull_tryAgain) +chapterIndex);
                }


            }
        });
    }

    @SuppressLint("ClickableViewAccessibility")
    private void initView(){
        infoTv = findViewById(R.id.infoTv);
        radioBtn = findViewById(R.id.radioBtn) ;

        ScrollView readerScrollView = findViewById(R.id.readerScrollView) ;
        readerScrollView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return radioBtn.isChecked();
            }
        });

        webView = findViewById(R.id.dataTextView);
        webView.getSettings().setDefaultTextEncodingName("UTF-8") ;
        webView.getSettings().setJavaScriptEnabled(false);
        webView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // 如果返回true ，就不能 禁止长按复制
                return false;
            }
        });

        int textSize =MMKV.defaultMMKV().decodeInt(SaveConfig.KEY_TEXTSIZE);
        int textColor =  MMKV.defaultMMKV().decodeInt(SaveConfig.KEY_COLOR);
        textSize= textSize==0 ? 100: textSize ;
        webView.getSettings().setTextZoom( textSize ); //设置字体大小
        webView.setBackgroundColor(textColor );

        findViewById(R.id.settingBtn).setOnClickListener(onClickListener);
        findViewById(R.id.exitBtn).setOnClickListener(onClickListener);
        findViewById(R.id.infoTv).setOnClickListener(onClickListener);
    }


    private int dataSize ;
    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            int i = v.getId();
            if (i == R.id.settingBtn) {
                showSettingWindow();
            } else if (i == R.id.exitBtn) {
                finish();
            } else if (i == R.id.infoTv) {
                getDataFromeServer(chapterIndex, false); // 重新加载
            }
        }
    };


    private ReadSettingPopuWindow readSettingPopuWindow;
    private View readRootView ;
    private void showSettingWindow() {
        if (readSettingPopuWindow == null) {
            readSettingPopuWindow = new ReadSettingPopuWindow(this,dataSize ,settingCallBack);
        }

        if(readRootView==null){
            readRootView = findViewById(R.id.readRootView) ;
        }
        readSettingPopuWindow.showAtLocation(readRootView, Gravity.BOTTOM, 0, 0);
    }

    private SettingCallBack settingCallBack = new SettingCallBack() {
        @Override
        public void onValueChange(int value, int type) {
            if(type==100){
                webView.getSettings().setTextZoom(value);
                MMKV.defaultMMKV().encode(SaveConfig.KEY_TEXTSIZE ,value) ;
            }
        }

        @Override
        public void onColorChange(int color) {
            webView.setBackgroundColor(color);
            MMKV.defaultMMKV().encode(SaveConfig.KEY_COLOR ,color) ;
        }

        @Override
        public void readNextData() {
            getDataFromeServer(++chapterIndex ,true);
        }

        @Override
        public void readPreData() {
            getDataFromeServer(--chapterIndex ,true);
        }
    };

}
